package com.eascs.admin.o2o.settle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.badloan.controller.O2oBadloanRestController;
import com.eascs.admin.o2o.badloan.entity.O2oBadRecordEntity;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oEaLoanDataEnity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.settle.entity.O2oSettleEntity;
import com.eascs.admin.o2o.settle.service.O2oSettleService;
import com.eascs.admin.o2o.settle.vo.O2oSettleVo;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.loan.vo.O2oRepaymentRecordVo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/rsettle")
public class O2oSettleRestController {
	private static Logger log = LoggerFactory.getLogger(O2oBadloanRestController.class);

	@Autowired
	O2oSettleService service;

	@Autowired
	O2oLoanService   o2oLoanService;

	@Value("${o2o.admin.settleurl}")
	String           startUrl;

	@Autowired
	private O2oLoanapplyService loanService;

	@Reference
	private WorkFlowService workFlowService;

	@Autowired
	private O2oBadLoanService badLoanService;

	@RequestMapping("/startUp")
	public BaseRestResult<String> startUp(O2oSettleVo vo) {
		O2oEaLoanDataEnity eaLoanDataEnity = badLoanService.findById(vo.getEaLoadId());
		User user = UserHolder.getUser();
		Date date = new Date();
		if (eaLoanDataEnity != null) {
			O2oBadRecordEntity badRecordEntity = new O2oBadRecordEntity();
			badRecordEntity.setBillCode(eaLoanDataEnity.getBillCodeEa());
			badRecordEntity.setLoanDataId(eaLoanDataEnity.getId());
			badRecordEntity.setFlowStatus(StatusContexts.O2O_BANK_RUN);// 查询已发起流程的单号
			O2oBadRecordEntity o2oBadRecordEntity1 = badLoanService.findRecordByFlowStatus(badRecordEntity);
			if (o2oBadRecordEntity1 != null) {
				// 如果流程已经启动则等流程走完后再次发起
				return BaseRestResult.warn("该单存在回款流程中，不能发起结清！");
			}
			O2oSettleEntity o2oSettleEntity = service.findEntity(vo);
			if (o2oSettleEntity == null) {
				o2oSettleEntity = new O2oSettleEntity();
				o2oSettleEntity.setBillCode(eaLoanDataEnity.getBillCodeEa());
				o2oSettleEntity.setLoanDataId(vo.getEaLoadId());
				o2oSettleEntity.setCreateTime(date);
				o2oSettleEntity.setLoanUserName(eaLoanDataEnity.getLoanerName());
				o2oSettleEntity.setCreateNo(user.getNo());
				o2oSettleEntity.setCreateName(user.getCname());
				o2oSettleEntity.setLtd(eaLoanDataEnity.getLtd());
				o2oSettleEntity.setLtdCode(eaLoanDataEnity.getLtdCode());
				o2oSettleEntity.setLtdName(eaLoanDataEnity.getLtdName());
				o2oSettleEntity.setDcTotal(eaLoanDataEnity.getPayAmount());
				o2oSettleEntity.setDcLoadTotal(eaLoanDataEnity.getPaymentAmount());
				o2oSettleEntity.setFlowStatus(StatusContexts.O2O_NEW);
				o2oSettleEntity.setIsDelete(StatusContexts.O2O_NO);
				service.insertEntity(o2oSettleEntity);
			} else {
				if (o2oSettleEntity.getFlowStatus().equals(StatusContexts.O2O_BANK_CLO)) {
					return BaseRestResult.warn("该单已结清，不能重复发起结清！");
				} else if (o2oSettleEntity.getFlowStatus().equals(StatusContexts.O2O_BANK_RUN)) {
					return BaseRestResult.warn("该单已有结清流程，不能重复发起结清！");
				}
			}
			ModelResult<Boolean> model = startPayBack(o2oSettleEntity);
			if (model.isSuccess()) {
				o2oSettleEntity.setFlowStartTiem(date);
				o2oSettleEntity.setFlowStartNo(user.getNo());
				o2oSettleEntity.setFlowStartName(user.getCname());
				o2oSettleEntity.setFlowStatus(StatusContexts.O2O_BANK_RUN);
				int i = service.updateById(o2oSettleEntity);
				if (i > 0) {
					log.info("代偿结清流程启动成功，启动id：【{}】", vo.getEaLoadId());
				}
				return BaseRestResult.info("流程启动成功").andRefresh();
			} else {
				log.info("代偿结清流程启动失败，启动id：【{}】，失败原因：【{}】", vo.getEaLoadId(), model.getDetailStack());
				return BaseRestResult.warn(model.getErrMsg());
			}
		} else {
			return BaseRestResult.warn("未查询到代偿数据信息，请联系管理员！");
		}
	}

	/**
	 * @Description:
	 * 				<p>
	 *               启动代偿结清流程
	 *               </p>
	 * @author CXW
	 * @date 2017年4月18日 下午5:12:47
	 * @version V1.0
	 */
	public ModelResult<Boolean> startPayBack(O2oSettleEntity o2oSettleEntity) { // 根据单号去启动流程
		ModelResult<Boolean> modelResult = new ModelResult<>();
		O2oLoanapplyEntity loan = loanService.fingByBillCode(o2oSettleEntity.getBillCode());
		O2oEaLoanDataEnity o2oEaLoanDataEnity = badLoanService.findById(o2oSettleEntity.getLoanDataId());
		if (o2oEaLoanDataEnity==null) {
			return modelResult.withError("error billCode O2O SQL not find", "代偿数椐异常，请检查数据是否正常");
		}
		if (null == loan) {
			return modelResult.withError("error billCode O2O SQL not find", "贷款单号异常，请检查数据是否正常");
		}
		// 获取 o2opay对象
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oSettleEntity.getLoanDataId());
		param.setReferCode(o2oSettleEntity.getBillCode());
		// 回款流程的url
		param.setReferUrl(startUrl + "?billCode=" + loan.getBillCode() + "&loanId=" + o2oSettleEntity.getLoanDataId());
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(ProcessTemplate.PROECESS_TYPE_DCJQ); // 修改成回款流程编号
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		List<String> excludeNodeCodeList =new ArrayList<String>();
		if ("LXDC".equals(o2oEaLoanDataEnity.getLoanType())) {
			excludeNodeCodeList.add("ZBDHFH");
			param.setExcludeNodeCodeList(excludeNodeCodeList);
		}
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(loanService.findLoanUserEntity(loan.getLoanapplyNo(), loan.getLoanId()).getUserFullName());
		appliedDes.append("，放款金额:");
		java.text.DecimalFormat df         = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		BigDecimal loanAmount=new BigDecimal(0);
		if ("EA".equals(loan.getLoanType())||"FQ".equals(loan.getLoanType())) {
			loanAmount = badLoanService.findDataByBillCode(loan.getBillCode()).getLoanAmount();
		}else{
			loanAmount = o2oLoanService.queryBillCode(loan.getBillCode()).getLoanAmount();
		}
		appliedDes.append(df.format(loanAmount));
		param.setAppliedDes(appliedDes.toString());
		log.info("启动代偿结清流程，参数有代偿id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", o2oSettleEntity.getId(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loan.getLtd(), appliedDes.toString());
		modelResult = workFlowService.instance(param);
		return modelResult;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               保存总部贷后表单
	 *               </p>
	 * @author CXW
	 * @date 2017年4月18日 下午5:03:44
	 * @version V1.0
	 */
	@RequestMapping("/update")
	public BaseRestResult<String> update(O2oSettleEntity o2oSettleEntity) {
		if (StringUtil.isEmpty(o2oSettleEntity.getSetlleTime())) {
			return BaseRestResult.warn("请选择结清时间");
		}
		if (StringUtil.isEmpty(o2oSettleEntity.getRemark())) {
			return BaseRestResult.warn("请填写备注");
		}
		O2oSettleEntity settleEntity = service.getById(o2oSettleEntity.getId());
		settleEntity.setSetlleTime(o2oSettleEntity.getSetlleTime());
		settleEntity.setRemark(o2oSettleEntity.getRemark());
		int i = service.updateById(settleEntity);
		if (i > 0) {
			return BaseRestResult.info("保存成功");
		} else {
			return BaseRestResult.warn("保存失败");
		}
	}

	/**
	 * @Description:
	 * 				<p>
	 *               总部贷后表单：结清日期、结清备注，可编辑
	 *               </p>
	 * @author CXW
	 * @date 2017年4月18日 下午5:04:53
	 * @version V1.0
	 */
	@RequestMapping("/view_settle")
	public BaseRestResult<String> viewUpdate(String referId) {
		O2oSettleVo vo = new O2oSettleVo();
		vo.setEaLoadId(referId);
		O2oSettleEntity settleEntity = service.findEntity(vo);
		ViewContext.put("settleEntity", settleEntity);
		return new HtmlRestResult("settle/view_update");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               财务复核流程表单：结清日期、结清备注，只读， 增加按钮【查看回款明细】按钮链接到代偿回款明细
	 *               </p>
	 * @author CXW
	 * @date 2017年4月18日 下午5:04:53
	 * @version V1.0
	 */
	@RequestMapping("/find_settle")
	public BaseRestResult<String> findNowPayment(O2oRepaymentRecordVo entity) {
		O2oSettleVo vo = new O2oSettleVo();
		vo.setEaLoadId(entity.getReferId());
		O2oSettleEntity settleEntity = service.findEntity(vo);
		ViewContext.put("settleEntity", settleEntity);
		ViewContext.put("type", entity.getType());
		return new HtmlRestResult("settle/find_view");
	}

	@Autowired
	private BaseUtils baseUtils;

	/**
	 * @Description:
	 * 				<p>
	 *               代偿结清详情
	 *               </p>
	 * @author CXW
	 * @date 2017年4月20日 下午1:52:10
	 * @version V1.0
	 */
	@RequestMapping("/approl_detail")
	public BaseRestResult<String> findSettleDetail(String id) {
		O2oEaLoanDataEnity o2oEaLoanDataEnity = badLoanService.findById(id);
		O2oLoanapplyEntity o2oLoanapplyEntity = loanService.findBillCode1(o2oEaLoanDataEnity.getBillCodeEa());
		log.info("工作流访问回款详情：参数billCode：【{}】，referId:【{}】", o2oEaLoanDataEnity.getBillCodeEa(), o2oEaLoanDataEnity.getId());
		String agreeUrl = baseUtils.getApprovalAgreeUrl(o2oEaLoanDataEnity.getId(), null, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("o2oEaLoanDataEnity", o2oEaLoanDataEnity);
		ViewContext.put("o2oLoanapplyEntity", o2oLoanapplyEntity);
		return HtmlRestResult.popHtmlFragment("settle/approl_detail");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               代偿结清代办界面
	 *               </p>
	 * @author CXW
	 * @date 2017年4月20日 下午2:03:49
	 * @version V1.0
	 */
	@RequestMapping("/approl")
	public BaseRestResult<String> recordView(O2oRepaymentRecordVo entity) {
		log.info("工作流访问回款详情：参数billCode：【{}】，referId:【{}】", entity.getBillCode(), entity.getReferId());
		O2oEaLoanDataEnity o2oEaLoanDataEnity = badLoanService.findById(entity.getReferId());
		O2oLoanapplyEntity o2oLoanapplyEntity = loanService.findBillCode1(o2oEaLoanDataEnity.getBillCodeEa());
		String approvalUrl = baseUtils.getApprovalUrl(entity.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		ViewContext.put("approvalUrl", approvalUrl);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(entity.getReferId(), entity.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalStatus", entity.getApprovalStatus());
		ViewContext.put("o2oEaLoanDataEnity", o2oEaLoanDataEnity);
		ViewContext.put("o2oLoanapplyEntity", o2oLoanapplyEntity);
		return HtmlRestResult.popHtmlFragment("settle/approl");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               删除代偿结清新建数据
	 *               </p>
	 * @author CXW
	 * @date 2017年4月20日 下午2:12:43
	 * @version V1.0
	 */
	@RequestMapping("/delete")
	public BaseRestResult<String> delete(String eaLoadId) {
		O2oSettleVo vo = new O2oSettleVo();
		vo.setEaLoadId(eaLoadId);
		O2oSettleEntity settleEntity = service.findEntity(vo);
		settleEntity.setIsDelete(StatusContexts.O2O_YES);
		int i = service.updateById(settleEntity);
		if (i > 0) {
			return BaseRestResult.info("删除成功").andRefresh();
		} else {
			return BaseRestResult.warn("删除失败").andRefresh();
		}
	}
}
